package com.knowledgepoint.study.config.mybatis;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

public class PhysicalDeleteByMap extends AbstractMethod {
    
    public PhysicalDeleteByMap() {
        super("physicalDeleteByMap");
    }
    
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = "<script>DELETE FROM %s %s</script>";
        String tableName = tableInfo.getTableName();
        String where = sqlWhereByMap(tableInfo);
        String sqlResult = String.format(sql, tableName, where);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
        return this.addDeleteMappedStatement(mapperClass, "physicalDeleteByMap", sqlSource);
    }
    
    protected String sqlWhereByMap(TableInfo tableInfo) {
        StringBuilder where = new StringBuilder();
        where.append("<where>");
        where.append("<foreach item='value' index='key' collection='cm' separator=' AND '>");
        where.append("${key} = #{value}");
        where.append("</foreach>");
        where.append("</where>");
        return where.toString();
    }
}
